package com.speciality.demo.demos.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.speciality.demo.demos.entity.WeatherDaily;
import com.speciality.demo.demos.entity.WeatherHourly;
import com.speciality.demo.demos.mapper.WeatherDailyMapper;
import com.speciality.demo.demos.mapper.WeatherHourlyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/weather")
public class WeatherController {
    @Autowired
    private WeatherHourlyMapper weatherHourlyMapper;

    @Autowired
    private WeatherDailyMapper weatherDailyMapper;

    // 查询每小时天气数据
    @GetMapping("/hourly")
    public List<WeatherHourly> getHourlyWeather(
            @RequestParam String startTime,
            @RequestParam String endTime) {

        QueryWrapper<WeatherHourly> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("time", startTime, endTime)
                .orderByAsc("time");

        return weatherHourlyMapper.selectList(queryWrapper);
    }

    // 查询每日天气数据
    @GetMapping("/daily")
    public List<WeatherDaily> getDailyWeather(
            @RequestParam LocalDate startDate,
            @RequestParam LocalDate endDate) {

        QueryWrapper<WeatherDaily> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("date", startDate, endDate)
                .orderByAsc("date");

        return weatherDailyMapper.selectList(queryWrapper);
    }

    // 批量插入每小时数据
    @PostMapping("/hourly/batch")
    public boolean batchInsertHourly(@RequestBody List<WeatherHourly> hourlyList) {
        return hourlyList.stream()
                .allMatch(item -> weatherHourlyMapper.insert(item) > 0);
    }

    // 获取特定日期的温度范围
    @GetMapping("/daily/temperature-range")
    public Map<String, Object> getTemperatureRange(@RequestParam LocalDate date) {
        QueryWrapper<WeatherDaily> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("date", date)
                .select("temperature2m_max", "temperature2m_min");

        WeatherDaily daily = weatherDailyMapper.selectOne(queryWrapper);

        Map<String, Object> result = new HashMap<>();
        if (daily != null) {
            result.put("maxTemperature", daily.getTemperature2mMax());
            result.put("minTemperature", daily.getTemperature2mMin());
            result.put("date", date);
        }

        return result;
    }
}
